<?php
// +----------------------------------------------------------------------
// | 登录服务服务层
// +----------------------------------------------------------------------
// | 主要服务于登录数据处理
// +----------------------------------------------------------------------
// | 错误编码头 209xxx
// +----------------------------------------------------------------------
namespace common\service;

use common\exception\LogicException;
use common\model\UserModel;
use support\bootstrap\Redis;
use support\ErrorCode;
use support\SingletonTrait;

class LoginService
{

    // 错误信息
    protected $errorMessage = "";

    // 单例工具
    use SingletonTrait;

    /**
     * 获取错误信息
     */
    public function getError()
    {
        return $this->errorMessage;
    }

    /**
     * 同步用户基本信息
     * @param $userData
     * @param bool $updateUser 是否更新用户
     * @return array|bool|string|null
     */
    public function syncUserBasicData($userData, $updateUser = true)
    {
        $userModel = model(UserModel::class);
        $userDataIn = [
            'phone' => $userData['phone'],
            'email' => $userData['email'],
            'name' => $userData['name'],
            'union_id' => $userData['id'],
            'avatar' => !empty($userData['avatar']) ? $userData['avatar'] : "",
        ];
        $user = $userModel->where(['union_id' => $userData['id']])->find();
        if (empty($user)) {
            //不存在用户就先添加用户
            $user = $userModel->addItem($userDataIn);
            if ($user == false) {
                throw new LogicException($userModel->getError(), $userModel->getErrorCode());
            }
        } else {
            if ($updateUser) {
                $userDataIn['id'] = $user['id'];
                $userModel->modifyItem($userDataIn);
            }
        }
        return $user;
    }

    /**
     * 查询自己的用户信息
     * @param $userId
     * @param bool $syncUserData
     * @param float|int $syncCacheTime
     * @return array
     */
    public function getUserInfo($userId, $syncUserData = true, $syncCacheTime = 60 * 60)
    {
        $data = teamones_request('teamones-im', 'user/get_my_user_info', []);
        $data = $data['data'];

        if (empty($data['user'])) {
            throw new LogicException("login failed", ErrorCode::LOGIN_FAILED);
        }
        if (empty($data['tenant']) || empty($data['tenant']['id'])) {
            throw new LogicException("missing tenant", ErrorCode::MISSING_TENANT);
        }
//        if (empty($data['department_info'])) {
//            throw new Exception("missing department_info", ErrorCode::MISSING_ROLE);
//        }

//        $departmentId = 0;
//        $roleId = 0;
//        foreach ($data['department_info'] as $departmentInfo) {
//            if (isset($departmentInfo['role_id']) && $departmentInfo['role_id'] > 0) {
//                $roleId = $departmentInfo['role_id'];
//            }
//            if (isset($departmentInfo['department_id']) && $departmentInfo['department_id'] > 0) {
//                $departmentId = $departmentInfo['department_id'];
//            }
//        }
//
//        if ($departmentId === 0) {
//            throw new Exception("missing department", ErrorCode::MISSING_DEPARTMENT);
//        }
//
//        if ($roleId === 0) {
//            throw new Exception("missing role", ErrorCode::MISSING_ROLE);
//        }

        if ($syncUserData) {
            $lockKey = 'sync_user_basic_info:' . $data['user']['id'];
            $syncFlag = Redis::get($lockKey);
            if (empty($syncFlag)) {
                Redis::setEx($lockKey, $syncCacheTime, 1);
                $this->syncUserBasicData($data['user']);
            }
        }
        $data['saas_user'] = model(UserModel::class)->field("json", true)->find($userId);
        return $data;
    }

    /**
     * 获取当前用户部门信息
     * @return array|mixed
     * @throws \Exception
     */
    public function getDepartmentInfo()
    {
        $data = teamones_request('teamones-im', 'user/get_my_user_info', null)['data'];
        if (empty($data['user'])) {
            throw new LogicException("login failed", ErrorCode::LOGIN_FAILED);
        }
        if (empty($data['tenant']) || empty($data['tenant']['id'])) {
            throw new LogicException("missing tenant", ErrorCode::MISSING_TENANT);
        }
        return $data['department_info'] ?? [];
    }

    /**
     * 同步用户基本信息
     * @param $remoteUserList
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function syncUserBasicDataBatch($remoteUserList)
    {
        $userModel = model(UserModel::class);
        $remoteUserMap = array_column($remoteUserList, null, 'id');
        $unionIDs = array_keys($remoteUserMap);
        $users = $userModel->where(['union_id' => ['IN', implode(',', $unionIDs)]])->select();
        //查询出的用户和预期的用户数量不等 那么从远端获取一次用户
        if (count($users) != count($unionIDs)) {
            $usersAssoc = array_column($users, null, 'union_id');
            $syncIds = array_filter($unionIDs, function ($item) use (&$usersAssoc) {
                return isset($usersAssoc[$item]) == false;
            });
            foreach ($syncIds as $unionId) {
                $remoteUserItem = $remoteUserMap[$unionId];
                $userDataIn = [
                    'phone' => $remoteUserItem['phone'],
                    'email' => $remoteUserItem['email'],
                    'name' => $remoteUserItem['name'],
                    'union_id' => $remoteUserItem['user_id'],
                    'avatar' => !empty($remoteUserItem['avatar']) ? $remoteUserItem['avatar'] : "",
                ];
                $flag = $userModel->addItem($userDataIn);
                if ($flag === false) {
                    trace("[{$userModel->getErrorCode()}]" . $userModel->getError(), 'WARN');
                } else {
                    $users[] = $flag;
                }
            }
        }
        return $users;
    }
}
